<?php

class DefaultController extends Controller
{
	public $layout='column2';
	public $defaultAction='view';
	
	public function actions()
	{
		return array(
				'invoice' => 'user.components.ActionInvoice',
		);
	}
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			array('ESetReturnUrlFilter + view',),
			array('SetSaveAttributesFilter + pay',),
		);
	}
	
	
	
	public function actionView()
	{
		$model=User::model()->with('service')->findbyPk(Yii::app()->user->id);

		$serviceModel=new Service('search');
		if(isset($_GET['Service']))
			$serviceModel->attributes=$_GET['Service'];
		$serviceModel->user_id=$model->id;
		
		$paymentModel=new Payment('search');
		if(isset($_GET['Payment']))
			$paymentModel->attributes=$_GET['Payment'];
		$paymentModel->user_id=$model->id;

		$this->render('view',array(
			'model'=>$model,
			'serviceModel'=>$serviceModel,
			'paymentModel'=>$paymentModel,
		));
		
		$session=new CHttpSession;
		$session->open();
  		$session['back_url']=Yii::app()->request->requestUri;  // Сохранение адреса возврата
	}
	
	public function actionPay()
	{
		$model=new Payment;
		
		$model->is_prepayment=1;
		$date = new DateTime(date('Y-m-d'));
		$model->payment_date=date_format($date, 'd.m.Y');
		date_add($date,new DateInterval('P'.Setting::get('PrePaymentDays').'D'));
		$model->prepayment_date=date_format($date, 'd.m.Y');
		$model->user_id=Yii::app()->user->id;

		// Uncomment the following line if AJAX validation is needed
		if(isset($_POST['ajax']) && $_POST['ajax']==='payment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_POST['Payment']))
		{
			$model->attributes=$_POST['Payment'];
			if($model->save()) {
				if (!Yii::app()->request->isAjaxRequest) {
					$this->redirect(Yii::app()->user->returnUrl);
				} else return true;
			}
		}

		$this->render('pay',array(
			'model'=>$model,
		));
	}

}